<template>
  <div class="login-container">
    <van-nav-bar
      title="登录/注册"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form
      :show-error="false"
      :show-error-message="false"
      validate-first
      ref="form-login"
      @submit="onLoginIn"
      @failed="onFailed"
    >
      <van-cell-group>
        <van-field
          v-model="user.mobile"
          label="手机号"
          :colon="true"
          center
          icon-prefix="icon"
          name="mobile"
          left-icon="shouji"
          :rules="rules.mobile"
        />
        <van-field
          v-model="user.code"
          label="验证码"
          :colon="true"
          name="code"
          center
          icon-prefix="icon"
          left-icon="ecurityCode"
          :rules="rules.code"
        >
          <template #button>
            <van-count-down v-if="isCountdown" format="ss s" :time="1000 * 60" @finish="isCountdown = false" />
            <van-button v-else size="small" :loading="isCaptchaLoading" loading-type="spinner" type="default" @click.prevent="onCaptcha">发送验证码</van-button>
          </template>
        </van-field>
      </van-cell-group>
      <div class="btn_login_wrap">
        <van-button type="primary" class="btn_login" block>登录</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import { login, captcha } from '@/api/login'
export default {
  name: 'loginIndex',
  data () {
    return {
      // 表单数据
      user: {
        mobile: '18279995475',
        code: '246810'
      },
      // 表单验证规则
      rules: {
        mobile: [
          {
            required: true,
            message: '请填写手机号码'
          },
          {
            pattern: /^1[3|5|7|8|9][0-9]\d{8}$/,
            message: '手机号码格式错误'
          }
        ],
        code: [
          {
            required: true,
            message: '请填写手机验证码'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码错误'
          }
        ]
      },
      isCountdown: false, // 是否显示验证码倒计时
      isCaptchaLoading: false // 发送验证码默认显示不加载状态
    }
  },
  methods: {
    // 登录
    async onLoginIn () {
      // 登录加载
      this.$toast.loading({
        message: '登录中...',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 0
      })

      try {
        const res = await login(this.user)
        // 登录成功提示
        this.$toast.success('登录成功')

        // 登录成功保存token到共享容器
        this.$store.commit('setUser', res.data.data)

        // 清除 layout 的缓存，让它重新渲染
        this.$store.commit('removeCachePage', 'layoutIndex')

        // 登录成功,跳转我的页面
        this.$router.push(this.$route.query.redirect || '/')
      } catch (err) {
        // 登录失败提示
        this.$toast.fail('登录失败')
        return Promise.reject(err)
      }
    },

    // 表单验证失败
    onFailed (values) {
      if (values.errors[0]) {
        this.$toast({
          message: values.errors[0].message,
          position: 'top'
        })
      }
    },

    // 验证码
    async onCaptcha () {
      // 发送验证码,进入加载状态
      this.isCaptchaLoading = true
      try {
        // 手机号码验证成功
        await this.$refs['form-login'].validate('mobile')
        // 发送验证码
        await captcha(this.user.mobile)
        // 开始倒计时
        this.isCountdown = true
      } catch (err) {
        // 错误提示
        let message = ''
        // 判断错误类型,显示相对应的错误提示
        if (err && err.response && err.response.status === 429) {
          // 发送短信失败的错误提示
          message = '发送太频繁,请稍后重试'
        } else if (err.name === 'mobile') {
          // 手机号码验证失败,错误提示
          message = err.message
        } else {
          // 未知错误
          message = '发送失败，请稍后重试'
        }

        // 提示用户
        this.$toast({
          message,
          position: 'top'
        })
      }
      // 无论是否发送验证码都关闭按钮的加载状态
      this.isCaptchaLoading = false
    }
  }
}
</script>
<style lang="less">
.login-container{
  .van-cell-group{
    .van-cell{
      .van-field__label{
        width: 60px;
        font-size: 12px;
      }
      .van-field__value{
        .van-button--small{
          background: #ededed;
          .van-button__text{
            color:#666666;
            font-size: 11px;
          }
        }
      }
    }
  }
  .btn_login_wrap{
    padding: 26px 16px;
    .btn_login{
      background: #3296fa;
      border: 1px solid #3296fa;
      font-size: 15px;
    }
  }
}
</style>
